// 当前页面的 reducer
import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit'
import { RootState, AppThunk } from 'store/store'
import { fetchLogin, LoginParamsType } from './loginApi'

// // redux-thunk代码
// export const incrementAsync = createAsyncThunk('counter/fetchCount', async (amount: number) => {
//   const response = await fetchCount(amount)
//   // The value we return becomes the `fulfilled` action payload
//   return response.data
// })

export const fetchLoginAsync = createAsyncThunk('login/fetchLogin', async ({ username, password }: LoginParamsType) => {
  console.log('reduce thunk:', username, password)
  const response = await fetchLogin({ username, password })
  return response.data
})

const loginSlice = createSlice({
  name: 'login',
  initialState: {
    token: '',
    loading: '',
  },
  reducers: {
    changeStatus(state, action) {
      state.loading = action.payload
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(fetchLoginAsync.pending, (state) => {
        console.log('state:loading....', state)
        // state.loading = 'loading...'
      })
      .addCase(fetchLoginAsync.fulfilled, (state, action) => {
        console.log(state, 'state---action:', action)
        state.token = action.payload.token
      })
  },
})

export const { changeStatus } = loginSlice.actions

export default loginSlice.reducer

// reducer -> slice 切片
// export interface CounterState {
//   value: number
//   status: 'idle' | 'loading' | 'failed'
// }

// const initialState: CounterState = {
//   value: 0,
//   status: 'idle',
// }

// // reducer
// export const counterSlice = createSlice({
//   // 命名空间
//   name: 'counter',
//   // 数据仓库
//   initialState,
//   // 处理同步逻辑地方 vuex-mutaion
//   reducers: {
//     increment: (state) => {
//       state.value += 1
//     },
//     decrement: (state) => {
//       state.value -= 1
//     },
//     incrementByAmount: (state, action: PayloadAction<number>) => {
//       state.value += action.payload
//     },
//   },
//   // 处理异步逻辑--vuex action
//   extraReducers: (builder) => {
//     builder
//       .addCase(incrementAsync.pending, (state) => {
//         state.status = 'loading'
//       })
//       .addCase(incrementAsync.fulfilled, (state, action) => {
//         state.status = 'idle'
//         state.value += action.payload
//       })
//   },
// })

// export const { increment, decrement, incrementByAmount } = counterSlice.actions

// // 取出 state中的数据
// export const selectCount = (state: RootState) => state.counter.value

// // 异步action
// export const incrementIfOdd =
//   (amount: number): AppThunk =>
//   (dispatch, getState) => {
//     const currentValue = selectCount(getState())
//     if (currentValue % 2 === 1) {
//       dispatch(incrementByAmount(amount))
//     }
//   }

// export default counterSlice.reducer
